<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr>
    <input type="text" maxlength="10" v-model="newComments.user_name" placeholder="请输入用户名">
    <textarea cols="30" rows="4" placeholder="请输入评论内容，最多120个字符" maxlength="120" v-model="content"></textarea>
    <mt-button type="primary" size="large" @click="postComments">发表评论</mt-button>

    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, index) in comments" :key="index">
        <div class="cmt-title">
          第{{ index + 1 }}楼&nbsp;&nbsp;用户：{{ item.user_name }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFormat }}
        </div>
        <div class="cmt-body">
          {{ item.content === "undefined" ? "此用户很懒，什么都没说" : item.content }}
        </div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMoreComments">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageIndex: 1,
      comments: [],
      content: "",
      newComments: {
        art_id: this.$route.params.id,
        user_name: "匿名用户"
      }
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      // 获取相关评论
      this.$http
        .get(
          "getcomments?artid=" +
            this.newComments.art_id +
            "&pageindex=" +
            this.pageIndex
        )
        .then(result => {
          if (result.status === 200)
            // 获取新评论时，在老数据后追加新获取到的数据
            this.comments = this.comments.concat(result.body);
          else Toast("评论加载失败");
        });
    },
    getMoreComments() {
      this.pageIndex++;
      this.getComments();
    },
    postComments() {
      // 去除评论前后空格
      this.newComments.content = this.content.trim();
      // 校验是否为空
      if (this.newComments.content.length === 0)
        return Toast("评论内容不能为空");
      this.$http.post("postcomments", this.newComments).then(result => {
        if (result.status === 200) {
          this.newComments.add_time = Date.now();
          this.comments.unshift(this.newComments);
          this.content = "";
          Toast("评论成功");
          //this.getComments();
        } else Toast("评论失败 " + result);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  input[type="text"] {
    font-size: 14px;
    margin: 0;
    color: #999;
  }
  textarea {
    font-size: 14px;
    height: 85px;
    margin: 0;
  }
  .cmt-list {
    margin: 5px 0;
    .cmt-item {
      font-size: 13px;
      .cmt-title {
        line-height: 30px;
        background-color: #ccc;
      }
      .cmt-body {
        line-height: 35px;
        text-indent: 2em;
      }
    }
  }
}
</style>

